import React, { useState } from 'react';
import { Modal, Form, Row, Col, Input, TreeSelect, InputNumber, Radio, message } from 'antd';
import { endsWith } from 'lodash';
import { FormInstance } from 'antd/es/form/Form';
import { AIconPreview } from '@/components/SelfComp/AIconPreview';
import ASelect, { ASelectOptionType } from '@/components/SelfComp/ASelect';
import { DataItem, FormModalProps } from '@/types/global';
import { MenuItem, MenuSelectTreeItem } from '@/types/menu';
import { formLayout, modalFormItemLayout, maxModalFormItemLayout } from '@/utils/commons';

type AddMenuProps<T> = FormModalProps<T> & {
  menuTypeData: DataItem[];
  menuActionData: DataItem[];
  menuTreeData: MenuSelectTreeItem[];
  hideInMenuData: DataItem[];
}

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const AddMenuModal: React.FC<AddMenuProps<MenuItem>> = (props) => {
  /** 按钮功能栏位是否可见，true-类型为按钮，false-类型为菜单 */
  const [btnActionVisible, setBtnActionVisible] = useState<boolean>(false);
  /** 菜单是否隐藏栏位是否可见 */
  const [hideInMenuVisible, setHideInMenuVisible] = useState<boolean>(true);
  /** 路由地址栏位是否可见，true-显示，false-不显示 */
  const [routeAddVisible, setRouteAddVisible] = useState<boolean>(true);
  /** 图标弹窗是否可见，true-显示，false-不显示 */
  const [iconViewVisible, setIconViewVisible] = useState<boolean>(false);
  const { colon, modalTitle, modalWidth, modalVisible, menuTypeData, menuTreeData, loading, formData } = props;
  const { menuActionData, hideInMenuData } = props;
  const { menuType, menuId, parentMenuId, menuCode } = formData;
  // 当勾选的是页面或弹窗，显示自己
  // 当勾选的是按钮或接口，显示父节点
  const tmpParentId = menuType === '1' || menuType === '3' ? menuId + '' : parentMenuId + '';
  const tmpMenuCode = menuCode ? `${menuCode}:`: '';
  const formItemLayout = modalFormItemLayout;
  const formRef = React.createRef<FormInstance>();

  const onOk = () => {
    formRef.current!.validateFields().then(fieldsValue => {
      console.info(fieldsValue);
      const values = {
        ...fieldsValue
      };
      const { menuCode } = values;
      if (endsWith(menuCode, ':')) {
        message.warn('菜单权限编码不合法，请检查');
        return;
      }
      console.log('Received values of form: ', values);
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        onHandlerOK({
          ...values
        });
      }
    }).catch();
  };

  const onCancel = () => {
    // 先清除form表单
    formRef.current!.resetFields();
    const { onHandlerCancel } = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 菜单类型栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const menuTypeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    // 查询该功能码对应的交易信息
    // console.log('menuTypeChange');
    formRef.current!.resetFields([
      'menuAction', 'menuIcon'
    ]);
    // 菜单类型为2-按钮时，显示按钮位置栏位
    if (value === '2') {
      setBtnActionVisible(true);
      setHideInMenuVisible(false);
      setRouteAddVisible(false);
      return;
    }
    if (value === '1' || value === '3') {
      setBtnActionVisible(false);
      setHideInMenuVisible(true);
      setRouteAddVisible(true);
      return;
    }
    setBtnActionVisible(false);
    setRouteAddVisible(true);
  }

  /**
   * 菜单图标点击事件，展示图标预览弹窗
   */
  const menuIconOnClick = () => {
    setIconViewVisible(true);
  }

  const handleIconViewOk = ({icon} : {icon: string}) => {
    console.log(icon);
    setIconViewVisible(false);
    const menuIcon = icon;
    formRef.current!.setFieldsValue({
      menuIcon
    });
  }

  const handleIconViewCancel = () => {
    setIconViewVisible(false);
  };

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      maskClosable={false}
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} ref={formRef}>
        <Row>
          <Col span={24}>
            <FormItem label="上级菜单" name='parentMenuId' {...maxModalFormItemLayout} colon={colon}
              initialValue={tmpParentId}
            >
              <TreeSelect
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={menuTreeData}
                allowClear
                showSearch
                treeNodeFilterProp="title"
                placeholder="请选择"
              />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label="菜单权限类型" name='menuType' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '菜单权限类型必输' }
              ]}
              initialValue={'1'}
            >
              <ASelect dataSource={menuTypeData} onChange={menuTypeChange}/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="菜单权限名称" name='menuName' {...formItemLayout} colon={colon}
              rules={[
                { max: 10, message: '菜单权限名称最多允许输入10个字符' },
                { required: true, message: '菜单权限名称必输' }
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        {
          !routeAddVisible ? null :
          <Row>
            <Col span={24}>
              <FormItem label="路由地址" name='menuPath' {...maxModalFormItemLayout} colon={colon}
                rules={[
                  { required: routeAddVisible, message: '路由地址必输' },
                  { max: 50, message: '路由地址最多允许输入50个字符' },
                  { pattern: new RegExp(/^\/[A-Za-z][A-Za-z0-9\/-]{1,50}$/, "g"), message: '路由地址只能以/字母开头，由A-Za-z0-9组成，最大长度为50' }
                ]}
              >
                <Input/>
              </FormItem>
            </Col>
          </Row>
        }
        <Row>
          <Col span={12}>
            <FormItem label="菜单图标" name='menuIcon' {...formItemLayout} colon={colon}
              rules={[
                { required: routeAddVisible, message: '菜单图标必输' }
              ]}
            >
              <Input readOnly onClick={menuIconOnClick}/>
            </FormItem>
          </Col>
          {
            !btnActionVisible ? null :
            <Col span={12}>
              <FormItem label="按钮位置" name='menuAction' {...formItemLayout} colon={colon}
                rules={[
                  { required: btnActionVisible, message: '按钮位置必输' }
                ]}
              >
                <ASelect dataSource={menuActionData}/>
              </FormItem>
            </Col>
          }
          {
            !hideInMenuVisible ? null :
            <Col span={12}>
              <FormItem label="菜单是否显示" name='hideInMenu' {...formItemLayout} colon={colon}
                tooltip='选择隐藏则菜单不会出现在左侧菜单栏，但仍可以访问'
                rules={[
                  { required: hideInMenuVisible, message: '菜单是否显示必输' }
                ]}
              >
                <ASelect dataSource={hideInMenuData}/>
              </FormItem>
            </Col>
          }
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='菜单权限编码' name='menuCode' {...formItemLayout} colon={colon}
              initialValue={tmpMenuCode}
              rules={[
                { max: 20, message: '菜单权限编码最多允许输入20个字符' },
                { required: true, message: '菜单权限编码必输' },
                { pattern: new RegExp(/^[A-Za-z][A-Za-z0-9-_:]{1,20}$/, "g"), message: '菜单权限编码只能以字母开头，由A-Za-z0-9组成，最大长度为20' }
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='菜单权限别名' name='menuAlias' {...formItemLayout} colon={colon}
              rules={[
                { max: 20, message: '菜单权限别名最多允许输入20个字符' },
                { required: true, message: '菜单权限别名必输' },
                { pattern: new RegExp(/^[A-Za-z][A-Za-z0-9-_]{1,20}$/, "g"), message: '菜单权限别名只能以字母开头，由A-Za-z0-9组成，最大长度为20' }
              ]}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label="显示排序" name='menuSort' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '显示排序必输' }
              ]}
            >
              <InputNumber min={0} style={{ width: '100%' }}/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="新窗口打开" name='newOpen' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '新窗口打开必输' }
              ]}
              initialValue='1'
            >
              <RadioGroup name="newOpen">
                <Radio value={'1'}>否</Radio>
                <Radio value={'2'}>是</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
        </Row>
      </Form>
      {
        !iconViewVisible ? null :
        <AIconPreview
          modalTitle='选择图标'
          modalWidth={1000}
          modalVisible={iconViewVisible}
          onHandlerOK={handleIconViewOk}
          onHandlerCancel={handleIconViewCancel}
        />
      }
    </Modal>
  );
}

export default AddMenuModal